<?php
namespace app\api\controller;

use think\Exception;
use \think\Request;
use \think\Db;
use think\Session;
use think\Config;
use think\Controller;

class Store extends Base
{
    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-15
     * @rewriter:
     * @rewriter_date:
     * @description:商家信息-全部商品
     * @param:
     * @return json
     */
    public function allProductInfo(){
        $data = Request::instance()->post();

//            && array_key_exists('type', $data)
//            && array_key_exists('search', $data)
//            && array_key_exists('category_id', $data)
//            && array_key_exists('type_id', $data)
//            && array_key_exists('small_type_id', $data)
//            && array_key_exists('brand_id', $data))
        if (!empty($data['supplier_id']) && !empty($data['page_no']))
        {
            if ($data['type'] == 'all'){
                $where  = [
                    'P.name'     => ['like','%'.trim($data['search']).'%'],
                    'P.supplier'                => $data['supplier_id'],
                    'P.status'                  => 1,
                    'P.is_shelves'              => 1,
                    'Ps.is_default'             => 1,
                ];
            }else{
                if (empty($data['category_id'])&& empty($data['type_id'])&& empty($data['small_type_id'])&&
                    empty($data['brand_id'])){
                    $where  = [
                        'P.name'     => ['like','%'.trim($data['search']).'%'],
                        'P.supplier'                => $data['supplier_id'],
                        'P.status'                  => 1,
                        'P.is_shelves'              => 1,
                        'Ps.is_default'             => 1,
                    ];
                }elseif (!empty($data['category_id'])&& empty($data['type_id'])){
                    $where  = [
                        'P.name'     => ['like','%'.trim($data['search']).'%'],
                        'P.supplier'                => $data['supplier_id'],
                        'P.status'                  => 1,
                        'P.is_shelves'              => 1,
                        'P.category_id'             => $data['category_id'],
                        'Ps.is_default'             => 1,
                    ];
                }elseif (!empty($data['category_id'])&& !empty($data['type_id'])&& empty($data['small_type_id'])){
                    $where  = [
                        'P.name'     => ['like','%'.trim($data['search']).'%'],
                        'P.supplier'                => $data['supplier_id'],
                        'P.status'                  => 1,
                        'P.is_shelves'              => 1,
                        'P.category_id'             => $data['category_id'],
                        'P.type_id'                 => $data['type_id'],
                        'Ps.is_default'             => 1,
                    ];
                }elseif (!empty($data['category_id'])&& !empty($data['type_id'])&& !empty($data['small_type_id'])&&
                    empty($data['brand_id'])){
                    $where  = [
                        'P.name'     => ['like','%'.trim($data['search']).'%'],
                        'P.supplier'                => $data['supplier_id'],
                        'P.status'                  => 1,
                        'P.is_shelves'              => 1,
                        'P.category_id'             => $data['category_id'],
                        'P.type_id'                 => $data['type_id'],
                        'P.small_type_id'           => $data['small_type_id'],
                        'Ps.is_default'             => 1,
                    ];
                }elseif (!empty($data['category_id'])&& !empty($data['type_id'])&& !empty($data['small_type_id'])&&
                    !empty($data['brand_id'])){
                    $where  = [
                        'P.name'     => ['like','%'.trim($data['search']).'%'],
                        'P.supplier'                => $data['supplier_id'],
                        'P.status'                  => 1,
                        'P.is_shelves'              => 1,
                        'P.category_id'             => $data['category_id'],
                        'P.type_id'                 => $data['type_id'],
                        'P.small_type_id'           => $data['small_type_id'],
                        'P.brand_id'                => $data['brand_id'],
                        'Ps.is_default'             => 1,
                    ];
                }
            }
            $pageNo     = $data['page_no'];
            $pageSize   = 4;
            if (!empty($data['page_size'])){
                $pageSize   = $data['page_size'];
            }
            $product['list'] = Db::table('product')
                ->alias('P')
                ->field('P.id, P.name as product_name, Ps.specification, Ps.packing_proportion,
                    P.image as product_image, Ps.price, Ps.unit')
                ->join('product_specification Ps','Ps.product_id = P.id')
                ->where($where)
                ->limit(($pageNo-1)*$pageSize,$pageSize)
                ->select();
//            $sql = Db::name('product')->getLastSql();
            $product['count'] = count($product['list']);
            $total_count = Db::table('product')
                ->alias('P')
                ->join('product_specification Ps','Ps.product_id = P.id')
                ->where($where)
                ->count();
            if ($product['list']){
                $time  = date("Y-m-d H:i:s", time());
                foreach ($product['list'] as $k=>$v){
                    $product['list'][$k]['price'] =  number_format($v['price'],2,'.','');
                    //是否收藏该商品.
                    if (array_key_exists('user_id', $data)){
                        if (!empty($data['user_id'])){
                            $where2  = [
                                'product_id'     => $v['id'],
                                'user_id'        => $data['user_id'],
                                'flag'           => 1,
                                'is_del'         => 0,
                            ];
                            $collect = Db::table('user_collect_product')
                                ->where($where2)
                                ->count();
                            if ($collect>0){
                                $product['list'][$k]['collect'] = 1;
                            }else{
                                $product['list'][$k]['collect'] = 0;
                            }
                        }else{
                            $product['list'][$k]['collect'] = 0;
                        }
                    }
                    //是否有活动
                    $where3  = [
                        'product_id'          => $v['id'],
                        'status'              => 1,
                        'start_time'          => ['<=',$time],
                        'end_time'            => ['>=',$time]
                    ];
                    $count = Db::table('discount')
                        ->where($where3)
                        ->count();
                    if ($count>0){
                        $product['list'][$k]['is_discount'] = 1;
                    }else{
                        $product['list'][$k]['is_discount'] = 0;
                    }
                }
                $result = Config::get('code.success');
                $result['product']      = $product;
                $result['total_count']  = $total_count;
            }else{
                $result = Config::get('code.null');
//                $result['sql'] = $sql;
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-15
     * @rewriter:
     * @rewriter_date:
     * @description:商家信息-收藏
     * @param:
     * @return json
     */
    public function storeCollect(){
        $data = Request::instance()->post();
        if (!empty($data['supplier_id']) && !empty($data['user_id'])){
            $data['is_del']         = 0;
            $data['collect_time']   = date("Y-m-d H:i:s",time());
            $data['flag']           = 1;
            $count = Db::table('user_collect')
                ->where(['user_id' => $data['user_id'], 'supplier_id' => $data['supplier_id'], 'is_del' => 0])
                ->find();
            if (!empty($count)){
                Db::table('user_collect')
                    ->where(['user_id' => $data['user_id'], 'supplier_id' => $data['supplier_id'], 'is_del' => 0])
                    ->update(['is_del'=>1]);
                $result['status'] = 209;
                $result['msg']    = '已收藏该商家';
                return json($result);
            }
            if (array_key_exists('sign',$data)){
                unset($data['sign']);
            }
            $res = Db::table('user_collect')->insert($data);
            if ($res){
                $result = Config::get('code.success');
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-15
     * @rewriter:
     * @rewriter_date:
     * @description:商家信息-基本信息
     * @param:
     * @return json
     */
    public function storeBasic(){
        $data = Request::instance()->post();
        file_put_contents('test.txt',json_encode($data));
        if (!empty($data['supplier_id'])){
            $supplier = Db::table('supplier')
                ->field('name, image, tel, star, manager_tel, shop_introduction, business, email, address, send_time_type, is_open')
                ->where(['id'=>$data['supplier_id']])
                ->find();
//            $arr = explode(',',$supplier['business']);
            $business = Db::name('base_data')->whereIn('id',$supplier['business'])->select();
            $arr = [];
            $arr_english = [];
            foreach ($business as $val){
                $arr[] = $val['name'];
                $arr_english[] = $val['name_english'];
            }
            $str = implode(',',$arr);
            $str_english = implode(',',$arr_english);
            $supplier['business'] = $str;
            $supplier['business_english'] = $str_english;
            $supplier['send'] = [];
            if (!empty($data['user_id'])){
                $is_collect = Db::table('user_collect')->where(['user_id'=>$data['user_id'],'supplier_id'=>$data['supplier_id']])->count();
                if ($is_collect>0){
                    $supplier['is_collect'] = 1;
                }else{
                    $supplier['is_collect'] = 0;
                }
            }
            if ($supplier['send_time_type'] == '1'){                //周配送.
                if (!empty($data['city'])){
                    $where=[
                        'month'        => 0,
                        'send_area'    => $data['city']
                    ];
                }else{
                    $where=[
                        'month'  => 0
                    ];
                }
                $supplier['send'] = Db::table('supplier_send_manage')
                    ->field('day, month, send_area')
                    ->where(['supplier_id'=>$data['supplier_id']])
                    ->where($where)
                    ->order('day asc')
                    ->select();
//                var_dump($supplier);exit;
                $week           =   array("一","二","三","四","五","六","日");
                $week_english   =   array("Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday");
                foreach ($supplier['send'] as $k=>$v){
                    $supplier['send'][$k]['date']           = "周".$week[$v['day']-1];
                    $supplier['send'][$k]['date_english']   = $week_english[$v['day']-1];
                }
            }elseif ($supplier['send_time_type'] == '2'){           //月配送.
                if (!empty($data['city'])){
                    $where=[
                        'month'  => ['<>',0],
                        'send_area'    => $data['city']
                    ];
                }else{
                    $where=[
                        'month'  => ['<>',0],
                    ];
                }
                //$month = date('m');
                $supplier['send'] = Db::table('supplier_send_manage')
                    ->field('day, month, send_area')
                    ->where(['supplier_id'=>$data['supplier_id']])
                    ->where($where)
                    ->order('month asc')
                    ->order('day asc')
                    ->select();
                foreach ($supplier['send'] as $k=>$v){
                    $month_english=array("","Jan.","Feb.","Mar.","Apr.","May.","Jun.","Jul.","Aug.","Sept.","Oct.","Nov.","Dec.");
                    $supplier['send'][$k]['date']           = $v['month'].'月'.$v['day'].'日';
//                    $supplier['send'][$k]['date_english']   = $v['month'].'-'.$v['day'];
                    $supplier['send'][$k]['date_english']   = $month_english[$v['month']]. ' ' . $v['day'];
                }
            }
            if ($supplier){
                $result = Config::get('code.success');
                $result['supplier'] = $supplier;
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-16
     * @rewriter:
     * @rewriter_date:
     * @description:商家信息-认证信息
     * @param:
     * @return json
     */
    public function authentic(){
        $data = Request::instance()->post();
        if (!empty($data['supplier_id'])){
            $supplier = Db::table('supplier')
                ->field('id, name, image, company, address, tel, manager, manager_tel, business')
                ->where(['id'=>$data['supplier_id']])
                ->find();
            if ($supplier){
                $result = Config::get('code.success');
                $result['supplier'] = $supplier;
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-16
     * @rewriter:
     * @rewriter_date:
     * @description:商家信息-商家口碑
     * @param:
     * @return json
     */
    public function reputation(){
        $data = Request::instance()->post();
        if (!empty($data['supplier_id'])){
            $comment['list'] = Db::table('comment_to_supplier')
                ->alias('C')
                ->field('U.id, U.name, U.image, U.addr, C.comment, C.store_star, C.time')
                ->join('user U','U.id = C.user_id')
                ->where(['C.supplier_id'=>$data['supplier_id']])
                ->limit(4)
                ->order('C.time desc')
                ->select();
            $comment['count'] = count($comment['list']);
            $total_count = Db::table('comment_to_supplier')
                ->alias('C')
                ->join('user U','U.id = C.user_id')
                ->where(['C.supplier_id'=>$data['supplier_id']])
                ->count();
            if ($comment['list']){
                foreach ($comment['list'] as $k=>$v){
                    $comment['list'][$k]['time'] = date('Y/m/d',strtotime($v['time']));
                }
                $result = Config::get('code.success');
                $result['comment']      = $comment;
                $result['total_count']  = $total_count;
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-16
     * @rewriter:
     * @rewriter_date:
     * @description:商家信息-用户评价(全部,低分,最新)
     * @param:
     * @return json
     */
    public function storeComment(){
        $data = Request::instance()->post();
//        return json($data);
        if (!empty($data['supplier_id']) && !empty($data['type']) && !empty($data['page_no'])){
            $where = [];
            if ($data['type'] == '1'){
//                $type = 'C.store_star';
                $type = 'C.time';
                $sort = 'desc';
            }elseif ($data['type'] == '2'){
//                $type = 'C.store_star';
                $type = 'C.time';
                $sort = 'desc';
                $where['C.store_star'] = array('<',3);
            }elseif ($data['type'] == '3'){
                $type = 'C.time';
                $sort = 'desc';
            }else{
                return json(Config::get('code.mistake'));
            }
            $pageNo     = $data['page_no'];
            $pageSize   = 6;
            $comment    = Db::table('comment_to_supplier')
                ->alias('C')
                ->field('U.id ,U.name, U.image, U.addr, C.comment, C.store_star, C.time')
                ->join('user U','U.id = C.user_id')
                ->where(['C.supplier_id'=>$data['supplier_id']])
                ->where($where)
                ->limit(($pageNo-1)*$pageSize,$pageSize)
                ->order("{$type} $sort")
                ->select();
            $total_count = Db::table('comment_to_supplier')
                ->alias('C')
                ->join('user U','U.id = C.user_id')
                ->where(['C.supplier_id'=>$data['supplier_id']])
                ->count();
            if (!empty($data['is_web'])){
                $comment = Db::table('comment_to_supplier')
                    ->alias('C')
                    ->field('U.id ,U.name, U.image, U.addr, C.comment, C.store_star, C.time')
                    ->join('user U','U.id = C.user_id')
                    ->where(['C.supplier_id'=>$data['supplier_id']])
                    ->where($where)
                    ->order("{$type} $sort")
                    ->paginate(9,false,['path'=>'javascript:ajax_page([PAGE]);','type'=>'BootstrapDetailed','var_page'=>'page_no']);
                $list = $comment->toArray();
                if ($list['data']){
                    foreach ($list['data'] as $k=>$v){
                        $list['data'][$k]['time'] = date('Y/m/d',strtotime($v['time']));
                    }
                    $result = Config::get('code.success');
                    $result['comment']      = $list;
                    $result['html']         = $comment->render();
                }else{
                    $result = Config::get('code.null');
                }
            }else{
               if ($comment){
                   foreach ($comment as $k=>$v){
                       $comment[$k]['time'] = date('Y/m/d',strtotime($v['time']));
                   }
                   $result = Config::get('code.success');
                   $result['data']  = $comment;
                   $result['count'] = count($comment);
                   $result['total']  = $total_count;
               }else{
                   $result = Config::get('code.null');
               }
            }

        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-01-16
     * @rewriter:
     * @rewriter_date:
     * @description:商家信息-商品分类
     * @param:
     * @return json
     */
    public function classify(){
        $data = Request::instance()->post();
        if (!empty($data['supplier_id'])&& array_key_exists('category_id', $data)
            && array_key_exists('type_id', $data)&& array_key_exists('small_type_id', $data)
            && array_key_exists('brand_id', $data))
        {
            if (empty($data['category_id'])){
                $join = [
                    ['product P' ,'P.category_id = B.id'],
                    ['supplier S','S.id = P.supplier'],
                ];
                $where  = [
                    'B.flag'            => 1,
                    'B.type_menu'       => 1,
                    'P.status'          => 1,
                    'P.is_shelves'      => 1,
                ];
            }elseif (empty($data['type_id'])){
                $join = [
                    ['product P' ,'P.type_id = B.id'],
                    ['supplier S','S.id = P.supplier'],
                ];
                $where  = [
                    'B.flag'            => 1,
                    'B.type_menu'       => 1,
                    'P.category_id'     => $data['category_id'],
                    'P.status'          => 1,
                    'P.is_shelves'      => 1,
                ];
            }elseif (empty($data['small_type_id'])){
                $join = [
                    ['product P' ,'P.small_type_id = B.id'],
                    ['supplier S','S.id = P.supplier'],
                ];
                $where  = [
                    'B.flag'            => 1,
                    'B.type_menu'       => 1,
                    'P.category_id'     => $data['category_id'],
                    'P.type_id'         => $data['type_id'],
                    'P.status'          => 1,
                    'P.is_shelves'      => 1,
                ];
            }elseif (empty($data['brand_id'])){
                $join = [
                    ['product P' ,'P.brand_id = B.id'],
                    ['supplier S','S.id = P.supplier'],
                ];
                $where  = [
                    'B.flag'            => 1,
                    'B.type_menu'       => 2,
                    'P.category_id'     => $data['category_id'],
                    'P.type_id'         => $data['type_id'],
                    'P.small_type_id'   => $data['small_type_id'],
                    'P.status'          => 1,
                    'P.is_shelves'      => 1,
                ];
            }
            $where['S.id'] = $data['supplier_id'];
            $classify['list'] = Db::table('base_data')
                ->alias('B')
                ->field('B.id, B.name, B.name_english,B.image,B.type_menu')
                ->join($join)
                ->where($where)
                ->group('B.id')
                ->select();
            if ($classify['list']){
                $classify['count'] = count($classify['list']);
                $result = Config::get('code.success');
                $result['classify']  = $classify;
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    public function checkCollect(){
        $post = \request()->post();
        try{
            $re = Db::name('user_collect')
                ->where('user_id',$post['user_id'])
                ->where('supplier_id',$post['supplier_id'])
                ->where('flag',1)
                ->where('is_del',0)
                ->find();
            if(!empty($re)){
                $res['status'] = 200;
                $res['msg'] = '已搜藏';
            }else{
                $res['status'] = 202;
                $res['msg'] = '未收藏';
            }
        }catch (Exception $exception ){
            $res['status'] = 201;
            $res['msg'] = '参数错误';
        }
        return json($res);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-03-14
     * @rewriter:
     * @rewriter_date:
     * @description:增加商店浏览次数
     * @param:
     * @return json
     */
    public function browseNum(){
        $data = Request::instance()->post();
        if (!empty($data['supplier_id'])&&!empty($data['user_id'])){
            $browse = Db::table('supplier_browse')->where(['supplier_id'=>$data['supplier_id'],'user_id'=>$data['user_id']])->find();
            if ($browse){
                $time     = date("Y-m-d",time());
                $now_time = strtotime($time);
                $old_time = strtotime($browse['date']);
                if ($now_time != $old_time){
                    $re  = Db::table('supplier_browse')->where(['supplier_id'=>$data['supplier_id'],'user_id'=>$data['user_id']])->setInc('browse_num',1);
                    $re1 = Db::table('supplier_browse')->where(['supplier_id'=>$data['supplier_id'],'user_id'=>$data['user_id']])->setField('date',$time);
                    if ($re&&$re1){
                        $result = Config::get('code.success');
                    }else{
                        $result = Config::get('code.error');
                    }
                }else{
                    $result = Config::get('code.success');
                }
            }else{
                $info['supplier_id']    = $data['supplier_id'];
                $info['user_id']        = $data['user_id'];
                $info['browse_num']     = 1;
                $info['date']           = date("Y-m-d",time());
                $re = Db::table('supplier_browse')->insert($info);
                if ($re){
                    $result = Config::get('code.success');
                }else{
                    $result = Config::get('code.error');
                }
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

    /**
     * @writer:wuqiubai
     * @DateTime:2018-02-27
     * @rewriter:xx
     * @rewriter_date:
     * @description:商家送货日期,用户地址,电话
     * @param:[]
     * @return[$result]
     */
    public function details(){
        $data = request()->post();
        if (!empty($data['user_id']) && !empty($data['supplier_id'])){
            $user               =   Db::table('user')->field('id, addr, phone, city, town')->where('id',$data['user_id'])->find();
            $send_time_type     =   Db::table('supplier')->where('id',$data['supplier_id'])->value('send_time_type');
            $is_open            =   Db::table('supplier')->where('id',$data['supplier_id'])->value('is_open');
            $send_date          =   '暂无配送';
            $discount           =   '--';
            $condition_money    =   0;
            $discount_money     =   0;
            if ($send_time_type == 1){                  //周配送.
                $send = Db::table('supplier_send_manage')
                    ->field('day, month, send_area')
                    ->where(['supplier_id'=>$data['supplier_id']])
                    ->where('month',0)
                    ->select();
                foreach ($send as $k=>$v){
                    if ($v['send_area'] == $user['city'] || $v['send_area'] == $user['town']){
                        $time = timeCompute(time());
                        $week = date('w');
                        if($week < $v['day']){
                            $time1 = ($v['day'] - $week)*24*60*60;
                            $date = strtotime($time['year'].'-'.$time['month'].'-'.$time['day'].' 00:00:00')+$time1;
                            $send_date = date("Y-m-d", $date);
                        }else{
                            $time1 = ( 7-($week-$v['day']))*24*60*60;
                            $date = strtotime($time['year'].'-'.$time['month'].'-'.$time['day'].' 00:00:00')+$time1;
                            $send_date = date("Y/m/d", $date);
                        }
                    }
                }
            }elseif ($send_time_type == 2){           //月配送.
                $send = Db::table('supplier_send_manage')
                    ->field('day, month, send_area')
                    ->where(['supplier_id'=>$data['supplier_id']])
                    ->where('month','<>',0)
                    ->select();
                foreach ($send as $k=>$v){
                    if ($v['send_area'] == $user['city'] || $v['send_area'] == $user['town']){
                        $time = timeCompute(time());
                        $send_date = $time['year'].'/'.$time['month'].'/'.$v['day'];
                    }
                }
            }
            $discount_info = Db::table('discount')
                ->field('id, type, condition_money, relief_money, give_product, start_time, end_time')
                ->where(['supplier_id'=>$data['supplier_id'], 'status'=>1])
                ->find();
            if ($discount_info){
                $time       = strtotime("now");
                $start_time = strtotime($discount_info['start_time']);
                $end_time   = strtotime($discount_info['end_time']);
                if ($start_time <= $time && $time <= $end_time){
                    if ($discount_info['type'] == 1){                //满减
//                        $discount           =   '满'.$discount_info['condition_money'].'减'.$discount_info['relief_money'];
                        $discount           =   '满减';
                        $condition_money    =   $discount_info['condition_money'];
                        $discount_money     =   $discount_info['relief_money'];
                    }elseif ($discount_info['type'] == 2){           //满送
//                        $discount           = '满'.$discount_info['condition_money'].'送'.$discount_info['give_product'];
                        $give               = Db::table('product_give')->where(['discount_id'=>$discount_info['id']])->find();
                        if ($give){
                            $give_product   = Db::table('product')->field('name, image')->where(['id'=>$give['product_id']])->find();
                            $give_product['count']   = $give['count'];
                        }
                        $discount           = '满送';
                        $condition_money    =   $discount_info['condition_money'];
                        $discount_money     = 0;
                    }
                }
            }
            $details['addr']            =  $user['addr'];
            $details['phone']           =  $user['phone'];
            $details['is_open']         =  $is_open;
            $details['send_area']       =  $send_date;
            $details['discount']        =  $discount;
            $details['condition_money'] =  $condition_money;
            $details['discount_money']  =  $discount_money;
            $details['give_product']    =  '';
            if (!empty($give_product)){
                $details['give_product']   =  $give_product;
            }
            if ($user){
                $result = Config::get('code.success');
                $result['details'] = $details;
            }else{
                $result = Config::get('code.null');
            }
        }else{
            $result = Config::get('code.mistake');
        }
        return json($result);
    }

}
